package com.yishusmt.wechatapi.wechatdev.utils;

import com.yishusmt.wechatapi.wechatdev.constant.WeChatConstant;
import com.yishusmt.wechatapi.wechatdev.entity.AccessToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;

/**
 * 获取临时素材工具
 *
 * @author zhangyi
 * @date 2018/8/29 14:10
 */
@Component
public class MediaUtil {

    /**
     * http请求方式: GET,https调用 获取素材列表
     */
    public static final String MEDIA_URL = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";

    /**
     * 获取临时素材
     */
    public static final String TEMPORARY_MATERIAL = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=ACCESS_TOKEN&media_id=MEDIA_ID";

    @Autowired
    private AccessTokenUtil accessTokenUtil;

    @Autowired
    private HttpClientUtil httpClientUtil;


    /**
     * (!!--此接口是高级权限接口，需要微信认证--!!)
     * 获取素材列表
     * type	是	素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
     * offset	是	从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * count	是	返回素材的数量，取值在1到20之间
     *
     * @return
     * @throws IOException
     */
    public String getMediaList() throws IOException, URISyntaxException {
        AccessToken accessToken = accessTokenUtil.getAccessToken();
        String url = MEDIA_URL.replace(WeChatConstant.ACCESS_TOKEN,accessToken.getAccess_token());
        String str = "{\n" +
                "    \"type\":image,\n" +
                "    \"offset\":0,\n" +
                "    \"count\":20\n" +
                "}";

        String connect = httpClientUtil.postConnect(url,str);
        System.out.println(connect);
        return connect;
    }


    /**
     * (!!--此接口是高级权限接口，需要微信认证--!!)
     *
     * 获取临时素材
     *
     * {"errcode":40007,"errmsg":"invalid media_id hint: [kCYzba00261335]"}
     * {"errcode":40007,"errmsg":"invalid media_id hint: [kCYzba00261335]"}
     * 高级接口....
     *
     * @return
     * @throws IOException
     * @throws URISyntaxException
     */
    public String getMedia() throws IOException, URISyntaxException {
        AccessToken accessToken = accessTokenUtil.getAccessToken();
        String url = TEMPORARY_MATERIAL
                .replace(WeChatConstant.ACCESS_TOKEN,accessToken.getAccess_token()
                .replace("MEDIA_ID","x7vihMImilM7XVTS--hf4pCBky7RUwIgoja-ACUK2Eup0zO21J8SaTa4fSXw9rnp"));

        String connect = httpClientUtil.getConnect(url);
        System.out.println(connect);
        return connect;
    }
}
